package com.springbootxuexi;

import com.springbootxuexi.domain.JsonResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 系统异常处理，比如：404,500
     * @param req
     * @param resp
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JsonResponse defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        logger.error("", e);
        JsonResponse r = null;

        if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
            r = new JsonResponse(404,"请求的页面无法找到",null);
        } else {
            r = new JsonResponse(500,"服务器内部错误",null);
        }

        r.setMessage(e.getMessage());
        return r;
    }
}
